package com.qg.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qg.pojo.QgGoods;
import com.qg.utils.Constants;
import com.qg.utils.RedisUtil;
import com.qg.vo.GoodsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

@Service
public class LocalGoodsServiceImpl implements LocalGoodsService {
    private static final Random rd = new Random();

    @Reference(version = "1.0.0")
    private QgGoodsService qgGoodsService;
    @Resource
    private RedisUtil redisUtil;

    public GoodsVo getGoodVoById(String id) throws Exception{
        //goods:id          goods的json字符串
        //1.判断缓存中是否存在该商品
        if(redisUtil.hasKey(Constants.KEY_GOODS+id)) {
            //如果存在，则从缓存中取出来
            GoodsVo vo = JSON.parseObject(redisUtil.getStr(Constants.KEY_GOODS+id),GoodsVo.class);
            return vo;
        }

        //如果不存在，从数据库查询出来，保存到缓存中
        //抢互斥锁，只有抢到了锁，才可以执行数据库的查询: 基于商品id，每个商品id，一把锁。 KEY_LOCK_GOODS_LOAD:id
        if(!redisUtil.lock(Constants.KEY_LOCK_GOODS_LOAD+id,2L)){
            Thread.sleep(100);
            return getGoodVoById(id);
        }

        QgGoods goods = qgGoodsService.getQgGoodsById(id);

        GoodsVo vo = new GoodsVo();
        vo.setId(goods.getId().toString());
        vo.setCurrentStock(goods.getStock());
        vo.setGoodsName(goods.getGoodsName());
        vo.setPrice(goods.getPrice());
        vo.setGoodsImg(goods.getGoodsImg());
        vo.setStock(goods.getStock());

        //通过随机过期时间，防止缓存雪崩
        redisUtil.setStr("goods:"+id, JSON.toJSONString(vo), rd.nextInt(5)+1L);

        return vo;
    }
}
